<?php
/**
 * 换算类
 */

namespace PKFrame\DataHandler;
defined('PATH_PK') or die();

class Convert
{

    /**
     * 字节数转换成带单位的文件大小字符串
     * @param int $size
     * @param null $unitFormat
     * @return string
     */
    public static function bytesToUnit($size = 0, $unitFormat = 'kb'): string
    {
        // 单位列表
        $Units_arr = array('b', 'kb', 'mb', 'gb', 'tb');
        $key = array_search($unitFormat, $Units_arr);
        $size /= pow(1024, $key);
        return number_format($size, 3) . $unitFormat;
    }

    public static function unitToBytes($Size, $UnitStr = NULL)
    {
        $Unit = preg_replace('/[^a-z]/', '', strtolower($Size));
        $Unit .= strpos($Unit, 'b') ? NULL : 'b';
        $Value = intval(preg_replace('/[^0-9]/', '', $Size));
        $Units = array('b' => 0, 'kb' => 1, 'mb' => 2, 'gb' => 3, 'tb' => 4);
        if ($UnitStr)
            $Exponent = isset($Units[$UnitStr]) ? $Units[$UnitStr] : 0;
        else
            $Exponent = isset($Units[$Unit]) ? $Units[$Unit] : 0;
        return ($Value * pow(1024, $Exponent));
    }
}